<template>
<!--  换销表记录页面-->
  <div class="app-container">
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div style="height: 96%; max-height:96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
            <el-tree
              :default-expanded-keys="defaultExpandedKeys"
              :data="sheetsTreeList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="sheetsCode"
              highlight-current
              v-loading="treeLoading"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data}">
                <div class="custom-tree-node"
                     style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                  <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                  <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                  <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                  <span>{{ node.label }}</span>
                  <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>

      <!--户表用量数据-->
      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <div style="width: 100%;margin: 10px 5px 10px 0;">
          <el-row class="line-bottom" v-show="showSearch">
            <el-col class="form_col">
              <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch"
                       :label-width="labelWidth">
                <div id="searchFilter" style="display: flex; justify-content: start; flex-wrap: wrap;">
                  <el-form-item label="记录类型" prop="logType">
                    <el-radio-group :size="formItemSize"
                                    style="width: 100%;"
                                    v-model="queryParams.logType"
                                    @input="handleLogTypeChange">
                      <el-radio-button label="exchange">换表记录</el-radio-button>
                      <el-radio-button label="terminate">销表记录</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
<!--                  <el-form-item label="表类型" prop="terminalClassify"-->
<!--                                v-if="queryParams.logType==='exchange'">-->
<!--                    <el-select :size="formItemSize"-->
<!--                               style="width: 100%;"-->
<!--                               v-model="queryParams.terminalClassify"-->
<!--                               @change="handleTerminalClassifyChange"-->
<!--                               placeholder="请选择表类型">-->
<!--                      <el-option label="户表" :value="2"></el-option>-->
<!--                      <el-option label="大用户表" :value="1"></el-option>-->
<!--                    </el-select>-->
<!--                  </el-form-item>-->

                  <el-form-item label="旧表编号" prop="oldTerminalId"
                                v-if="queryParams.logType==='exchange'">
                    <el-input :size="formItemSize"
                              style="width: 100%;"
                              v-model="queryParams.oldTerminalId"
                              placeholder="请输入旧表编号"
                              clearable
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                  <el-form-item label="新表编号" prop="newTerminalId"
                                v-if="queryParams.logType==='exchange'">
                    <el-input :size="formItemSize"
                              style="width: 100%;"
                              v-model="queryParams.newTerminalId"
                              placeholder="请输入新表编号"
                              clearable
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
<!--                  <el-form-item label="表类型" prop="terminalType"-->
<!--                                v-if="queryParams.logType==='terminate'">-->
<!--                    <el-select :size="formItemSize"-->
<!--                               style="width: 100%;"-->
<!--                               v-model="queryParams.terminalType"-->
<!--                               placeholder="请选择表类型">-->
<!--                      <el-option label="户表" :value="2"></el-option>-->
<!--                      <el-option label="大用户表" :value="1"></el-option>-->
<!--                    </el-select>-->
<!--                  </el-form-item>-->
                  <el-form-item label="用户编号" prop="userId"
                                v-if="queryParams.logType==='terminate'">
                    <el-input :size="formItemSize"
                              style="width: 100%;"
                              v-model="queryParams.userId"
                              placeholder="请输入用户编号"
                              clearable
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                  <el-form-item label="设备编号" prop="terminalId"
                                v-if="queryParams.logType==='terminate'">
                    <el-input :size="formItemSize"
                              style="width: 100%;"
                              v-model="queryParams.terminalId"
                              placeholder="请输入设备编号"
                              clearable
                              @keyup.enter.native="handleQuery"/>
                  </el-form-item>
                </div>
              </el-form>
            </el-col>

            <el-col class="form_query">
              <el-button v-show="collapseAble" type="text" size="mini" @click="shiftCollapseAble" class="text">
                    <span>
                      {{ fold ? '收起筛选' : '更多筛选' }}
                    </span>
              </el-button>
              <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
              <el-button @click="resetQuery" size="mini">重置</el-button>
              <RightDropdown :columns="replaceColumns" v-if="queryParams.logType==='exchange'" :queryVisible="false"
                             :showSearch.sync="showSearch" @queryTable="getList" class="ml10"
                             @export="handleExchangeExport"></RightDropdown>
              <RightDropdown :columns="terminateColumns" v-if="queryParams.logType==='terminate'" :queryVisible="false"
                             :showSearch.sync="showSearch" @queryTable="getList" class="ml10"
                             @export="handleTerminateExport"></RightDropdown>
            </el-col>
          </el-row>
<!--          <el-row :gutter="10" class="mb8">-->
<!--            -->
<!--          </el-row>-->

          <el-row>
            <el-table ref="replaceTable" key="replaceTable" v-loading="loading" :data="replaceList" border size="mini"
                      :height="getAvailableHeight" :default-sort="defaultSortReplace"
                      @sort-change="handleSorterChangeReplace" v-if="queryParams.logType==='exchange'">
              <el-table-column label="#" type="index" align="center" width="40" :show-overflow-tooltip="true"/>
              <el-table-column label="所属区域" align="center" prop="sheetsName" v-if="replaceColumns[0].visible" :show-overflow-tooltip="true"
                               sortable="custom" :sort-orders="['ascending', 'descending']" width="160"/>
              <el-table-column label="换表时间" align="center" prop="changeTime" width="145" :show-overflow-tooltip="true"
                               v-if="replaceColumns[8].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']">
              </el-table-column>
              <el-table-column label="表类型" align="center" prop="terminalClassify" width="90" :show-overflow-tooltip="true"
                               v-if="replaceColumns[1].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']">
                <template slot-scope="scope">
                  {{ ['大用户表', '户表'][parseInt(scope.row.terminalClassify) - 1] }}
                </template>
              </el-table-column>
              <el-table-column label="旧表编号" align="center" prop="oldTerminalId" v-if="replaceColumns[2].visible" :show-overflow-tooltip="true"
                               sortable="custom" :sort-orders="['ascending', 'descending']"/>
              <el-table-column label="旧表厂家" align="center" prop="oldSupplierId" width="100" :show-overflow-tooltip="true"
                               v-if="replaceColumns[3].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.oldSupplierId" :show-overflow-tooltip="true"/>
                </template>
              </el-table-column>
              <el-table-column label="旧表最后结算读数" align="center" prop="oldSettlementReading" :show-overflow-tooltip="true"
                               v-if="replaceColumns[4].visible" sortable="custom" width="160"
                               :sort-orders="['ascending', 'descending']"/>
              <el-table-column label="新表编号" align="center" prop="newTerminalId" v-if="replaceColumns[5].visible" :show-overflow-tooltip="true"
                               sortable="custom" :sort-orders="['ascending', 'descending']"/>
              <el-table-column label="新表厂家" align="center" prop="newSupplierId" width="100" :show-overflow-tooltip="true"
                               v-if="replaceColumns[6].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.terminal_supplier" :value="scope.row.newSupplierId" :show-overflow-tooltip="true"/>
                </template>
              </el-table-column>
              <el-table-column label="新表表底数" align="center" prop="newBaseReading" width="110" :show-overflow-tooltip="true"
                               v-if="replaceColumns[7].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']"/>
              <el-table-column label="操作人员" align="center" prop="operator" width="100" :show-overflow-tooltip="true"
                               v-if="replaceColumns[9].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']"/>
              <el-table-column label="备注" align="center" prop="remark" v-if="replaceColumns[10].visible" :show-overflow-tooltip="true"/>
            </el-table>

            <el-table ref="terminateTable" key="terminateTable" v-loading="loading" :data="terminateList" border
                      size="mini" :height="getAvailableHeight" :default-sort="defaultSortDelete"
                      @sort-change="handleSorterChangeDelete" v-if="queryParams.logType==='terminate'">
              <el-table-column label="#" type="index" align="center" width="40" :show-overflow-tooltip="true"/>
              <el-table-column label="所属区域" align="center" prop="sheetsName" key="sheetsName" :show-overflow-tooltip="true"
                               v-if="terminateColumns[0].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']"/>
              <el-table-column label="销表时间" align="center" prop="createTime" width="145" :show-overflow-tooltip="true"
                               v-if="replaceColumns[5].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']">
              </el-table-column>
              <el-table-column label="表类型" align="center" prop="terminalType" key="terminalType" width="90" :show-overflow-tooltip="true"
                               v-if="terminateColumns[1].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']">
                <template slot-scope="scope">
                  {{ ['大用户表', '户表'][parseInt(scope.row.terminalType) - 1] }}
                </template>
              </el-table-column>
              <el-table-column label="用户编号" align="center" prop="userId" key="userId" :show-overflow-tooltip="true"
                               v-if="terminateColumns[2].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']"/>
              <el-table-column label="设备编号" align="center" prop="terminalId" key="terminalId" :show-overflow-tooltip="true"
                               v-if="terminateColumns[3].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']"/>
              <el-table-column label="位置识别编号" align="center" prop="locationNb" key="locationNb" :show-overflow-tooltip="true"
                               v-if="terminateColumns[4].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']"/>
              <el-table-column label="操作人员" align="center" prop="operator" key="operator" :show-overflow-tooltip="true"
                               v-if="terminateColumns[6].visible" sortable="custom"
                               :sort-orders="['ascending', 'descending']"/>
            </el-table>
            <pagination
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {listMeterSheetsTree} from "@/api/basedata/meterSheets";
import {listReplace} from "@/api/logs/replace";
import {listAccount} from "@/api/logs/account";

export default {
  name: "ExChangeXb",
  dicts: ['terminal_supplier'],
  data() {
    return {
      // 默认展开的key
      defaultExpandedKeys: [],
      screenHeight: null,
      size: 'mini',
      collapseAble: false,
      fold: false,
      maxShow: 4,
      formItemSize: 'mini',
      labelWidth: '80px',
      defaultProps: {
        children: "children",
        label: "sheetsName",
      },
      // 区域树选项
      sheetsTreeList: [],
      replaceList: [],
      // 列信息
      replaceColumns: [
        {key: 0, label: `所属区域`, visible: true, dataIndex: 'sheetsName'},
        {key: 1, label: `表类型`, visible: true, dataIndex: 'terminalClassify'},
        {key: 2, label: `旧表编号`, visible: true, dataIndex: 'oldTerminalId'},
        {key: 3, label: `旧表厂家`, visible: true, dataIndex: 'oldSupplierId'},
        {key: 4, label: `旧表最后结算读数`, visible: true, dataIndex: 'oldSettlementReading'},
        {key: 5, label: `新表编号`, visible: true, dataIndex: 'newTerminalId'},
        {key: 6, label: `新表厂家`, visible: true, dataIndex: 'newSupplierId'},
        {key: 7, label: `新表表底数`, visible: true, dataIndex: 'newBaseReading'},
        {key: 8, label: `换表时间`, visible: true, dataIndex: 'endReading'},
        {key: 9, label: `操作人员`, visible: true, dataIndex: 'operator'},
        {key: 10, label: `备注`, visible: true, dataIndex: 'remark'},
      ],
      terminateList: [],
      terminateColumns: [
        {key: 0, label: `所属区域`, visible: true, dataIndex: 'sheetsName'},
        {key: 1, label: `表类型`, visible: true, dataIndex: 'terminalType'},
        {key: 2, label: `用户编号`, visible: true, dataIndex: 'userId'},
        {key: 3, label: `设备编号`, visible: true, dataIndex: 'terminalId'},
        {key: 4, label: `位置识别号`, visible: true, dataIndex: 'locationNb'},
        {key: 5, label: `销表时间`, visible: true, dataIndex: 'createTime'},
        {key: 6, label: `操作人员`, visible: true, dataIndex: 'operator'},
      ],
      // 默认排序
      defaultSortReplace: {prop: 'changeTime', order: 'descending'},
      defaultSortDelete: {prop: 'createTime', order: 'descending'},
      // 树状态
      treeVisible: true,
      // 遮罩层
      treeLoading: true,
      loading: false,
      // 显示搜索条件
      showSearch: true,
      reportType: '日用量',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        logType: 'exchange',
        sheetsCode: null,
        terminalClassify: 2,
        oldTerminalId: null,
        newTerminalId: null,
        terminalType: 2,
        userId: null,
        terminalId: null,
      },
      // 总条数
      total: 0,
      showtime: true,
      // 区域树筛选条件
      filterText: ''
    };
  },
  created() {
    this.screenHeight = document.body.clientHeight
    this.getTreeList(this.queryParams.terminalType)
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 215
    }
  },
  mounted() {
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
    this.getList()
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    /** 排序触发事件 */
    handleSorterChangeReplace({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getList()
    },
    handleSorterChangeDelete({column, prop, order}){
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getList()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      if (!this.queryParams.orderByColumn && this.queryParams.logType === 'exchange') {
        this.queryParams.orderByColumn = this.defaultSortReplace.prop
        this.queryParams.isAsc = this.defaultSortReplace.order
      }else if(!this.queryParams.orderByColumn && this.queryParams.logType === 'terminate'){
        this.queryParams.orderByColumn = this.defaultSortDelete.prop
        this.queryParams.isAsc = this.defaultSortDelete.order
      }
    },
    // 切换记录类型单选按钮
    handleLogTypeChange() {
      if(this.queryParams.logType === 'exchange') {
        this.defaultSortReplace.prop = 'changeTime'
        this.defaultSortReplace.order = 'descending'
        this.queryParams.orderByColumn = this.defaultSortReplace.prop
        this.queryParams.isAsc = this.defaultSortReplace.order
      }else if(this.queryParams.logType === 'terminate') {
        this.defaultSortDelete.prop = 'createTime'
        this.defaultSortDelete.order = 'descending'
        this.queryParams.orderByColumn = this.defaultSortDelete.prop
        this.queryParams.isAsc = this.defaultSortDelete.order
      }
      this.getList()
    },
    // 区域树节点点击事件
    handleNodeClick(data){
      this.queryParams.sheetsCode = data.sheetsCode
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    // 重置表单
    resetQuery() {
      this.$refs.tree.setCurrentKey(null);
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        logType: 'exchange',
        sheetsCode: this.$refs.tree.getCurrentNode()?.code,
        terminalClassify: 2,
        oldTerminalId: null,
        newTerminalId: null,
        terminalType: 2,
        userId: null,
        terminalId: null,
      }
      this.handleQuery()
    },
    // 获取表格数据
    getList() {
      this.checkSortColumn()
      this.loading = true;
      if (this.queryParams.logType === 'exchange') {
        // let choiceCheck = this.$refs.tree.getCurrentNode()
        // if (choiceCheck) {
        //   this.queryParams.sheetsCode = choiceCheck.code
        // }
        listReplace(this.queryParams).then(res => {
          this.loading = false;
          if (res.code === 200) {
            this.replaceList = res.rows
            this.total = res.total
          } else {
            this.$modal.msgError("数据查看失败!")
          }
        })
      } else {
        listAccount(this.queryParams).then(res => {
          this.loading = false;
          if (res.code === 200) {
            this.terminateList = res.rows
            this.total = res.total
          } else {
            this.$modal.msgError("数据查看失败!")
          }
        })
      }
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.sheetsName.indexOf(value) !== -1;
    },
    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true;
      // listMeterSheetsTree({}).then(response => {
      //   this.sheetsTreeList = response;
      //   this.treeLoading = false;
      // });
      this.sheetsTreeList = JSON.parse(localStorage.getItem('meteredTreeData'))
      if(this.sheetsTreeList.length === 0) {
        this.treeLoading = false;
      }else {
        this.defaultExpandedKeys = [this.sheetsTreeList[0].sheetsCode];
        this.treeLoading = false;
      }
    },
    // 改变tree的显示与隐藏
    changeTreeShow() {
      this.treeVisible = !this.treeVisible
    },
    /** 导出按钮操作 */
    handleExchangeExport() {
      this.download('basedata/replace/export', {
        ...this.queryParams,
      }, `换表记录数据.xlsx`)
    },
    /** 导出按钮操作 */
    handleTerminateExport() {
      this.download('basedata/account/export', {
        ...this.queryParams,
      }, `销表记录数据.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node{
    width: fit-content;
    min-width: var(--treeWidth);
  }
  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px ;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
</style>
